package com.yonyou.pmclouds.repeatwork.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.CommonProgramConsts;
import com.yonyou.pmclouds.billview.entity.BillViewQueryVO;
import com.yonyou.pmclouds.copyperson.entity.CopyPersonVO;
import com.yonyou.pmclouds.copyperson.rmiitf.ICopyPersonQuery;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.repeatwork.entity.RepeatWorkVO;
import com.yonyou.pmclouds.repeatwork.mapper.RepeatWorkMapper;
import com.yonyou.pmclouds.repeatwork.service.rmiitf.IRepeatWorkQuery;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

@Service(version = ApplicationConsts.APPLICATION_VERSION,interfaceClass = IRepeatWorkQuery.class)
public class RepeatWorkQueryImpl implements IRepeatWorkQuery, IPageQuerySerivce<RepeatWorkVO> {
    @Autowired
    private RepeatWorkMapper repeatWorkMapper;
    @Autowired
    private PictureRemoteService picService;
    @Autowired
    private ICopyPersonQuery copyPersonQuery;
    @Autowired
    private ProjectSimpleQuery projectSimpleQuery;
    @Autowired
    private OrganizationQuery organizationQuery;

    @Override
    public RepeatWorkVO[] queryByProject(QueryListParam queryListParam) throws BusinessException {
        RepeatWorkVO[] vos =repeatWorkMapper.queryByCondition(new String[]{queryListParam.getPkProject()}, null,  queryListParam.getStartDate(), queryListParam.getEndDate(), null,queryListParam.getPageStart(),queryListParam.getPageSize());

        return setRefFiledINfo(vos);
    }

    @Override
    public int countByProject(QueryListParam queryListParam) throws BusinessException {
        int count = repeatWorkMapper.countByCondition( new String[]{queryListParam.getPkProject()}, null,  queryListParam.getStartDate(), queryListParam.getEndDate(), null);
        return count;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.REPEATWORK_BILLTYPE;
    }

    @Override
    public RepeatWorkVO queryOneByPk(String pkRepeatwork) throws BusinessException {
        RepeatWorkVO repeatWorkVO = repeatWorkMapper.selectByPrimaryKey(pkRepeatwork);
        return repeatWorkVO;
    }

    @Override
    public RepeatWorkVO queryByProject(String pkProject) throws BusinessException {

        return null;
    }

    @Override
    public RepeatWorkVO getReport(String reportId) throws BusinessException {
        String[] pics = picService.queryPicNamesByPkEntity(reportId);
        RepeatWorkVO repeatWorkVO = repeatWorkMapper.selectByPrimaryKey(reportId);
        if(null != pics && pics.length > 0) {
            List<String> picLists = new ArrayList<>();
            //展示得时候过滤调文件（app要求，web卡片详情中没有展现出来所以不用考虑）
            for(String pic : pics){
                String[] elements = pic.split("\\.");
                if(null != elements || elements.length == 2){
                    String suffix = elements[1];
                    if(suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg")){
                        if(picLists.size() > 9){
                            break;
                        }
                        picLists.add(pic);
                    }
                }else{
                    throw new BusinessException("图片没有后缀");
                }

            }
            repeatWorkVO.setPictures(picLists.toArray(new String[0]));
            repeatWorkVO.setPicNum(pics.length);
        }
        wrapStatus(repeatWorkVO);

        List<String> list = new ArrayList<>();
        list.add(reportId);
        List<CopyPersonVO> copyPersonVOS = copyPersonQuery.queryByPkBills(list);
        if(null != copyPersonVOS && copyPersonVOS.size() > 0) {
            repeatWorkVO.setCopyPersons(copyPersonVOS);
        }
        //补充项目相关信息：项目编码、项目名称、项目对应的组织
        String pkProject = repeatWorkVO.getPkProject();
        ProjectVO projectVO = projectSimpleQuery.queryProject(pkProject);

        if(projectVO != null){
            repeatWorkVO.setProjectName(projectVO.getSname());
            repeatWorkVO.setProjectCode(projectVO.getScode());

            //可能存在没有项目组织的项目档案，所以后面不再对其组织进行翻译。
            if(projectVO.getPkOrg() ==null){
                return repeatWorkVO;
            }
            OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), projectVO.getPkOrg());
            if(organizationVO != null){
                repeatWorkVO.setOrgName(organizationVO.getSname());
                repeatWorkVO.setPkOrganization(organizationVO.getPkOrganization());
                repeatWorkVO.setPkOrgSrc(organizationVO.getPkSrc());
            }
        }

        return repeatWorkVO;
    }

    @Override
    public PageObject<Object> queryByCondition(String[] pkProject, String[] creators, String startDate, String endDate, int[] billStatus, int start, int size) throws BusinessException {
        int count = repeatWorkMapper.countByCondition(pkProject, creators, startDate, endDate, billStatus);
        RepeatWorkVO[] repeatWorkVOS = repeatWorkMapper.queryByCondition(pkProject, creators, startDate, endDate, billStatus, start, size);
        for (RepeatWorkVO vo : repeatWorkVOS) {
            //获取项目主键
            String pk = vo.getPkProject();
            ProjectVO projectVO = projectSimpleQuery.queryProject(pk);
            //赋值项目名
            vo.setProjectName(projectVO.getSname());
        }

        return new PageObject<Object>(repeatWorkVOS, count, start);
    }

    @Override
    public Map<String, RepeatWorkVO> queryByIDs(String[] ids) throws BusinessException {
        //强制截取长度，避免insql可能的问题
        if (ids.length > CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE) {
            ids = Arrays.copyOf(ids, CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE);
        }
        RepeatWorkVO[] repeatWorkVOs = repeatWorkMapper.queryByIds(ids);
        if(repeatWorkVOs==null || repeatWorkVOs.length==0){
            return new HashMap<>();
        }

        Map<String,RepeatWorkVO> repeatWorkVOMap = new HashMap<String,RepeatWorkVO>();

        for(RepeatWorkVO vo : repeatWorkVOs){
            repeatWorkVOMap.put(vo.getPkRepeatwork(),vo);
        }
        return repeatWorkVOMap;
    }

    @Override
    public PageObject<Object> queryByCondition(BillViewQueryVO billViewQueryVO) throws BusinessException {
        JSONObject extendsParams = billViewQueryVO.getExtendsParams();
        String[] pkorgs = extendsParams != null && StringUtils.isNotBlank(extendsParams.getString("pkorgs")) ? extendsParams.getString("pkorgs").split(",") : null;
        String tenantId = RuntimeEnvironment.getTenantId().trim();
        String[] pkProject = billViewQueryVO.getPkProject();
        int start = billViewQueryVO.getPageStart();
        String startDate = billViewQueryVO.getStartTime();
        String endDate = billViewQueryVO.getEndTime();
        int[] billStatus = billViewQueryVO.getBillStatus();
        String[] creators = billViewQueryVO.getCreators();
        int size = billViewQueryVO.getPageSize();
        //查询符合条件的复工单数量
        int count = repeatWorkMapper.countNewByCondition(pkProject, pkorgs,tenantId, creators, startDate, endDate, billStatus);
        //查询符合条件的复工单
        RepeatWorkVO[] repeatWorkVOS =repeatWorkMapper.queryNewByCondition(pkProject, pkorgs,tenantId,  creators, startDate, endDate, billStatus, start, size);
        //填充项目名称和项目编码
        fillProjectNameAndCode(repeatWorkVOS);
        //图片填充
        fillPics(repeatWorkVOS);
        //填充项目组织
        fillOrgs(repeatWorkVOS);
        return new PageObject<Object>(repeatWorkVOS, count, start);
    }

    @Override
    public RepeatWorkVO[] queryByStatus(String pkProject, int[] status) throws BusinessException {
        RepeatWorkVO[] repeatWorkVOS = repeatWorkMapper.queryByStatus(pkProject,status);
        return repeatWorkVOS;
    }

    private  void getPics(RepeatWorkVO[] repeatWorkVOS) throws BusinessException{
        List<String> entityies = new ArrayList<>();
        for(RepeatWorkVO vo:repeatWorkVOS){
            entityies.add(vo.getPkRepeatwork());
        }
        Map<String, List<String>> entitiesForPic = picService.queryPicsByPkEntitys(entityies.toArray(new String[0]));
        for(RepeatWorkVO vo:repeatWorkVOS){
            List<String> pics = entitiesForPic.get(vo.getPkRepeatwork());
            if(null == pics || pics.size() == 0){
                continue;
            }
            vo.setPictures(pics.toArray(new String[0]));
            vo.setPicNum(pics.size());
        }

    }

    /**
     * 处理参照字段，非必输项需校验空
     * @param vos
     * @return
     * @throws BusinessException
     */
    private RepeatWorkVO[] setRefFiledINfo(RepeatWorkVO[] vos) throws  BusinessException{
        if (ArrayUtils.isEmpty(vos)) {
            return new RepeatWorkVO[0];
        }

        Set<String> projectSet = new HashSet<String>();
        for(RepeatWorkVO vo: vos){
            projectSet.add(vo.getPkProject());
        }

        Map<String, ProjectVO> projectVOMap = projectSimpleQuery.queryProjects(projectSet.toArray(new String[0]));

        for (RepeatWorkVO vo: vos){
            vo.setProjectName(projectVOMap.get(vo.getPkProject()) == null ? null : projectVOMap.get(vo.getPkProject()).getSname());
            vo.setProjectCode(projectVOMap.get(vo.getPkProject()) == null ? null : projectVOMap.get(vo.getPkProject()).getScode());
        }

        return vos;
    }

    private void fillPics(RepeatWorkVO[] vos) throws BusinessException {
        List<String> entityies = new ArrayList<>();
        for(RepeatWorkVO repeatWorkVO : vos){
            entityies.add(repeatWorkVO.getPkRepeatwork());
        }
        Map<String, List<String>> entitiesForPic = picService.queryPicsByPkEntitys(entityies.toArray(new String[0]));
        for(RepeatWorkVO repeatWorkVO : vos){
            List<String> pics = entitiesForPic.get(repeatWorkVO.getPkRepeatwork());
            if(null == pics || pics.size() == 0){
                continue;
            }
            repeatWorkVO.setPictures(pics.toArray(new String[0]));
            repeatWorkVO.setPicNum(pics.size());
        }
    }

    private void fillProjectNameAndCode(RepeatWorkVO[] repeatWorkVOS) throws BusinessException {
        List<String> ids = new ArrayList<>();
        for (RepeatWorkVO repeatWorkVO : repeatWorkVOS) {
            ids.add(repeatWorkVO.getPkProject());
        }
        if(null == ids && ids.size() == 0){
            //do nothing
        }else{
            Map<String, ProjectVO> projectMap = projectSimpleQuery.queryProjects(ids.toArray(new String[0]));
            for (RepeatWorkVO repeatWorkVO : repeatWorkVOS) {
                ProjectVO projectVO = projectMap.get(repeatWorkVO.getPkProject());
                if(null != projectVO){
                    //赋值项目名
                    repeatWorkVO.setProjectName(projectVO.getSname());
                    repeatWorkVO.setProjectCode(projectVO.getScode());
                }else{
                    throw new BusinessException("项目没有查询到");
                }
            }
        }
    }

    private Map<String, OrganizationVO> obtailPkorgByProject(Map<String, ProjectVO> projectMap) throws BusinessException {
        Map<String, OrganizationVO> proToOrgMap = new HashMap<String, OrganizationVO>();
        if(projectMap != null && projectMap.size()> 0){
            List<String> pkOrgs = projectMap.values().stream().map(ProjectVO::getPkOrg).filter(vo -> StringUtils.isNotEmpty(vo)).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(pkOrgs)) {
                OrganizationVO[] organizationVOs = organizationQuery.queryByPkSrcs(RuntimeEnvironment.getTenantId(), pkOrgs.toArray(new String[0]));
                proToOrgMap = Arrays.stream(organizationVOs).filter(organizationVO -> StringUtils.isNotEmpty(organizationVO.getPkSrc()))
                        .collect(Collectors.toMap(OrganizationVO::getPkSrc, organizationVO -> organizationVO));
            }
        }
        return proToOrgMap;
    }

    private void fillOrgs(RepeatWorkVO[] repeatWorkVOS) throws BusinessException {
        List<String> pkProjects = Arrays.stream(repeatWorkVOS).map(RepeatWorkVO::getPkProject).collect(Collectors.toList());
        Map<String, ProjectVO> projectMap = projectSimpleQuery.queryProjects(pkProjects.toArray(new String[0]));
        obtailPkorgByProject(projectMap);
    }

    private void wrapStatus(RepeatWorkVO repeatWorkVO) {
        if (repeatWorkVO.getBillstatus() != null) {
            switch (repeatWorkVO.getBillstatus()) {
                case BillStatusConst.COMMON_APPROVING_STATUS:
                    repeatWorkVO.setStatus("审批中");
                    repeatWorkVO.setStrBillstatus("审批中");
                    break;
                case BillStatusConst.COMMON_REJECT_STATUS:
                    repeatWorkVO.setStatus("驳回");
                    repeatWorkVO.setStrBillstatus("驳回");
                    break;
                case BillStatusConst.COMMON_APPROVED_STATUS:
                    repeatWorkVO.setStatus("审批通过");
                    repeatWorkVO.setStrBillstatus("审批通过");
                    break;
                case BillStatusConst.COMMON_COMMIT_STATUS:
                    repeatWorkVO.setStatus("驳回后再提交");
                    repeatWorkVO.setStrBillstatus("驳回后再提交");
                    break;
                case BillStatusConst.COMMON_FREE_STATUS:
                    repeatWorkVO.setStatus("自由态");
                    repeatWorkVO.setStrBillstatus("自由态");
            }
        }
    }
}
